package com.wanqing.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wanqing.constant.MessageConstant;
import com.wanqing.context.BaseContext;
import com.wanqing.dto.*;
import com.wanqing.entity.*;
import com.wanqing.exception.AddressBookBusinessException;
import com.wanqing.exception.OrderBusinessException;
import com.wanqing.exception.ShoppingCartBusinessException;
import com.wanqing.mapper.*;
import com.wanqing.result.PageResult;
import com.wanqing.service.OrderService;
import com.wanqing.service.VoucherService;
import com.wanqing.vo.OrderStatisticsVO;
import com.wanqing.vo.OrderSubmitVO;
import com.wanqing.vo.OrderVO;
import com.wanqing.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private VoucherMapper voucherMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private VoucherService voucherService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId;
        //处理各种业务异常（地址簿为空，购物车数据为空）
        if (ordersSubmitDTO.getUserId()==null){
            userId = BaseContext.getCurrentId();
        }else {
            userId = ordersSubmitDTO.getUserId();
        }
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId(), userId);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户的购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //扣减图书库存
        for (ShoppingCart cart : shoppingCartList) {
            Book book = bookMapper.getById(cart.getBookId());
            if (book.getStock() < cart.getNumber()) {
                throw new OrderBusinessException("图书" + book.getName() + "库存不足");
            }
            Book newBook = new Book();
            newBook.setId(cart.getBookId());
            newBook.setStock(book.getStock() - cart.getNumber());
            bookMapper.update(newBook);
        }

        //封装订单实体类
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(userId);
        //封装订单提交数据传输类
        AsynSubmitOrderDTO asynSubmitOrderDTO = new AsynSubmitOrderDTO();
        asynSubmitOrderDTO.setShoppingCartList(shoppingCartList);
        asynSubmitOrderDTO.setOrders(orders);
        asynSubmitOrderDTO.setUserVoucherId(ordersSubmitDTO.getUserVoucherId());
        //异步提交订单信息
        try {
            rabbitTemplate.convertAndSend(
                    "submit.order.topic",
                    "submit.order.success",
                    asynSubmitOrderDTO
            );
        } catch (Exception e) {
            log.error("异步订单提交失败：{}", e.getMessage());
        }

        //封装VO 返回结果
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 异步订单系列提交
     * @param asynSubmitOrderDTO
     */
    @Override
    public void asynSubmitOrderSuccess(AsynSubmitOrderDTO asynSubmitOrderDTO) {
        List<ShoppingCart> shoppingCartList = asynSubmitOrderDTO.getShoppingCartList();
        Orders orders = asynSubmitOrderDTO.getOrders();
        Long userVoucherId = asynSubmitOrderDTO.getUserVoucherId();
        orderMapper.insert(orders);
        //向订单明细表插入n条数据
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //使用优惠券 更新用户优惠券状态
        if (userVoucherId != null && userVoucherId != 0) {
            voucherService.useVoucher(userVoucherId, orders.getId());
        }

        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(orders.getUserId());
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/

        //查询订单是否已支付
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        if (orders.getPayStatus() == Orders.PAID) {
            throw new OrderBusinessException("该订单已支付");
        }

        //异步完成订单支付
        try {
            rabbitTemplate.convertAndSend(
                    "pay.topic",
                    "pay.success",
                    ordersPaymentDTO.getOrderNumber()
            );
        } catch (Exception e) {
            log.error("异步订单支付失败：{}", e.getMessage());
        }
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder().id(ordersDB.getId()).status(Orders.TO_BE_CONFIRMED).payStatus(Orders.PAID).checkoutTime(LocalDateTime.now()).build();

        orderMapper.update(orders);

        // 通过WebSocket向客户端推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 1); // 1表示来单提醒 2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户端订单分页查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery4User(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 分页条件查询
        Page<OrderVO> orderVOS = orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(orderVOS.getTotal(), orderVOS.getResult());
    }
    /*
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQueryBck(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }*/

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        return orderMapper.details(id);
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    @Override
    public void userCancelById(Long id) {
        // 查询订单
        OrderVO orderVO = orderMapper.details(id);
        // 校验订单是否存在
        if (orderVO == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orderVO.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (Objects.equals(orderVO.getStatus(), Orders.TO_BE_CONFIRMED)) {
            // 待接单状态,给用户退款
            // 模拟退款成功，支付状态修改为退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 修改订单状态,已取消
        //取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

        //恢复库存
        orderVO.getOrderDetailList().forEach(orderDetail -> {
            Book book = bookMapper.getById(orderDetail.getBookId());
            Book newBook = new Book();
            newBook.setStock(book.getStock() + orderDetail.getNumber());
            bookMapper.update(newBook);
        });
        //退还优惠券
        voucherMapper.refundVoucher(orderVO.getId());
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的图书信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orderVOS = orderMapper.pageQuery(ordersPageQueryDTO);

        for (OrderVO orderVO : orderVOS) {
            List<String> orderBookList = orderVO.getOrderDetailList().stream().map(
                    orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber() + ";"
            ).collect(Collectors.toList());
            String orderBooks = String.join("", orderBookList);
            orderVO.setOrderBooks(orderBooks);
        }
        return new PageResult(orderVOS.getTotal(), orderVOS);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Transactional
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        OrderVO orderVO = orderMapper.details(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (orderVO == null || !orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        //Integer payStatus = orderVO.getPayStatus();
        /*if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderVO.getNumber(),
                    orderVO.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        //恢复库存
        orderVO.getOrderDetailList().forEach(orderDetail -> {
            Book book = bookMapper.getById(orderDetail.getBookId());
            Book newBook = new Book();
            newBook.setStock(book.getStock() + orderDetail.getNumber());
            bookMapper.update(newBook);
        });
        //退还优惠券
        voucherMapper.refundVoucher(orderVO.getId());
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Transactional
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        OrderVO orderVO = orderMapper.details(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = orderVO.getPayStatus();
        if (Objects.equals(orderVO.getStatus(), Orders.COMPLETED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        /*if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderVO.getNumber(),
                    orderVO.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        //恢复库存
        orderVO.getOrderDetailList().forEach(orderDetail -> {
            Book book = bookMapper.getById(orderDetail.getBookId());
            Book newBook = new Book();
            newBook.setStock(book.getStock() + orderDetail.getNumber());
            bookMapper.update(newBook);
        });
        //退还优惠券
        voucherMapper.refundVoucher(orderVO.getId());
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        OrderVO orderVO = orderMapper.details(id);

        // 校验订单是否存在，并且状态为3
        if (orderVO == null || !orderVO.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        OrderVO orderVO = orderMapper.details(id);

        // 校验订单是否存在，并且状态为4
        if (orderVO == null || !orderVO.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 根据订单id查询订单信息
        OrderVO orderVO = orderMapper.details(id);
        if (orderVO == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 通过WebSocket向客户端推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 2); // 1表示来单提醒 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orderVO.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
